#!/usr/bin/env python

import web, os, urllib, urllib2, yaml
from web import form
from xml.etree import ElementTree as et

fo = open("/var/www/apps/newzbin/config.yaml")
conf = yaml.load(fo.read())
username = conf["username"]
password = conf["password"]
sabserver = conf["sabnzbdserver"]
fo.close()

newzbinurl = "http://v3.newzbin.com/search/query/?"

urls = (
    '/', 'index',
    '/download/', 'download'
)

application = web.application(urls, globals()).wsgifunc()
app = web.application(urls, globals())
render = web.template.render('/var/www/apps/newzbin/html/')

movie = form.Form(
    form.Textbox('Movie', form.notnull),
    form.Textbox('Max Size', value=900),
)
tv = form.Form(
    form.Textbox('TV Show', form.notnull),
    form.Textbox('Max Size', value=500),
)


##This is all stuff needed for authentication...
passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
passman.add_password(None, newzbinurl, username, password)
authhandler = urllib2.HTTPBasicAuthHandler(passman)
opener = urllib2.build_opener(authhandler)
urllib2.install_opener(opener)



class index:
    def GET(self):
        movieform = movie()
        tvform = tv()
        return render.index()

    def POST(self):
        t = web.input(moviename='',maxsize='50000',tvshowname='',form='',appname='')
        if t.form == "movies":
            if not t.moviename:
                return "Movie field cannot be empty"
            nzbparams["category"] = 6
            nzbparams["u_post_smaller_than"] = t.maxsize
            nzbparams["q"] = t.moviename
            #return "Movie form\nMax Size: %s\nQuery: %s " % (t.maxsize,t.moviename)
        elif t.form == "tv":
            if not t.tvshowname:
                return "TV Show field cannot be empty"
            nzbparams["category"] = 8
            nzbparams["u_post_smaller_than"] = t.maxsize
            nzbparams["q"] = t.tvshowname
            #return "TV Showform\nMax Size: %s\nQuery: %s " % (t.maxsize,t.tvshowname)
        elif t.form == "app":
            if not t.appname:
                return "Application Name cannot be empty"
            nzbparams["category"] = 1
            nzbparams["u_post_smaller_than"] = t.maxsize
            nzbparams["q"] = t.appname
            #return "Application form\nMax Size: %s\nQuery: %s " % (t.maxsize,t.tvshowname)
        else: 
            return "You are playing around with my html ;-)"
        try:
            ourl = urllib2.urlopen(newzbinurl + urllib.urlencode(nzbparams))
            root = et.fromstring(ourl.read())
        except:
            return "error connecting to newzbin :("


        #start parsing the xml playa
        
        data = []
        items = [a for a in root[0].getchildren() if a.tag == "item"]
        for node in items:
            z = {}
            z["title"] = node.find("title").text[:55]
            z["category"] = t.form
            for a in node.getchildren():
                if "size" in a.tag:
                    z["size"] = int(a.text)/(1024*1024) 
                elif "nzb" in a.tag:
                    z["nzb"] = a.text
                elif "id" in a.tag:
                    z["id"] = a.text
            data.append(z)
            #data += "Title: %s\nSize: %sMB\n" % (title,size)
        return render.report(data)

class download:
    def POST(self):
        t = web.input(id=None)
        if t.id == None:
            return "Invalid id to download"
        try:
            fh = urllib2.urlopen('http://%s:8080/sabnzbd/api?mode=addid&name=%s&cat=%s' % (sabserver,t.id,t.category))
        except:
            return "SABnzbd isn't running...tell Patrick to start it up!!!!"
        
        out = fh.read()
        if "ok" in out:
            return '<a href="/"><h1>Success</h1></a>'
        else:
            return "I don't think it is downloading....better check"
        return "Hopefully we never get here"

    def GET(self):
        return '<a href="/">No GET has been specified</a>'
        
nzbparams = {'apply': 'Apply',
             'area': 'c.6',
             'areadone': 'c.6',
             'category': '6',
             'categoryasdf': 234,
             'hauth': 1,
             'feed': 'rss',
             'fpn': 'p',
             'q': 'test',
             'searchaction': 'Go',
             'u_comment_posts_only': '0',
             'u_completions': '1',
             'u_nfo_posts_only': '0',
             'u_post_results_amt': '20',
             'u_post_smaller_than': '900',
             'u_post_states': '0',
             'u_url_posts_only': '0',
             'u_use_exclusions': '1',
             'u_v3_retention': '0',}

if __name__ == "__main__": 
    app.run()
    
